package com.wei.shareand11

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File

class MainActivity : AppCompatActivity() {
    val TAG: String = "SHARE";
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        button.setOnClickListener {
            val permissions = Manifest.permission.WRITE_EXTERNAL_STORAGE
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val checkSelfPermission = checkSelfPermission(permissions)
                //获得系统权限之后将assets文件写入到应用目录
                if (checkSelfPermission == PackageManager.PERMISSION_GRANTED) {
                    val file = copyFileToProvider()
                    share(file)
                } else {
                    requestPermissions(arrayOf(permissions), 0)
                }
            }

        }
    }

    /**
     * 通过intent获取匹配的应用，为这些应用申请该uri文件的读取权限
     */
    @SuppressLint("QueryPermissionsNeeded")
    private fun grantPermission(intent: Intent, uri: Uri) {
        Log.e(TAG, "grantPermission:");
        packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
            .apply { Log.e(TAG, "grantPermission:$size") }.forEach {
                Log.e(TAG, "package:" + it.activityInfo.packageName)
                grantUriPermission(
                    it.activityInfo.packageName,
                    uri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION
                )
            }
    }


    /**
     * 拿到应用目录下的一个文件进行分享
     */
    private fun share(file: File) {
        val uri =
            FileProvider.getUriForFile(this, applicationInfo.packageName + ".fileProvider", file)
        val intent = Intent(Intent.ACTION_SEND).apply {
            type = getMineType(file.path)
            putExtra(Intent.EXTRA_STREAM, uri)
            setDataAndType(uri, type)
            addCategory(Intent.CATEGORY_DEFAULT)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
        }
        grantPermission(intent, uri)
        startActivity(intent)
    }

    fun getMineType(file: String): String? {
        try {

            val mmr = MediaMetadataRetriever()
            mmr.setDataSource(file)
            return mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
        } catch (e: Exception) {
            return "application/octet-stream";
        }
    }

    /**
     * 模拟一个从网上下载一个文件到应用的私有目录下
     */
    private fun copyFileToProvider(): File {
        val file = File(getExternalFilesDir(""), "file_temp_dir/kotlinstudy.md");
        Log.e(TAG, file.toString())
        file.run {
            parentFile?.mkdirs()
            if (!file.exists())
                file.createNewFile()
        }
        val uriForFile =
            FileProvider.getUriForFile(this, applicationInfo.packageName + ".fileProvider", file)
        Log.e(TAG, uriForFile.toString())
        val fos = contentResolver.openOutputStream(uriForFile)
        val fis = resources.assets.open("kotlinstudy.md")
        val byteArray = ByteArray(1024)
        try {
            fos.use { outputStream ->
                fis.use { inputStream ->
                    while (true) {
                        val readLen = inputStream.read(byteArray)
                        if (readLen == -1) {
                            break
                        }
                        outputStream?.write(byteArray, 0, readLen)
                    }
                }
            }
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return file;
    }

}